<?php

namespace app\system\service;

use app\model\SystemRole;
use app\model\SystemRoleMenu;
use app\traits\ServiceTrait;
use app\traits\UserTrait;
use think\db\Query;
use think\helper\Arr;

class RoleService
{
    use UserTrait;
    use ServiceTrait;

    public function save(array $params, $adminId = 0): array
    {
        $params['code'] = uniqid();
        $params['created_by'] = $this->getUid($adminId);
        return [true, SystemRole::create($params)];
    }

    /**
     * 添加用户可分配的角色，过滤管理员
     * @return array|\think\Collection|\think\db\BaseQuery[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getAvailableList()
    {
        return SystemRole::where('id', '>', 1)->select();
    }
    public function getList(?array $params, $select = ['*'], $sample = false)
    {
        $query = SystemRole::order(['sort' => 'desc']);
        if ($name = Arr::get($params, 'name')) {
            $query->where(['name' => $name]);
        }
        if ($code = Arr::get($params, 'code')) {
            $query->where(['code' => $code]);
        }
        if ($status = Arr::get($params, 'status')) {
            $query->where(['status' => $status]);
        }
        $pagination = $query
            ->field($select)
            ->paginate([
                'list_rows' => Arr::get($params, $this->listRowsName('system'), 15),
                'var_page' => 'page',
            ]);
        return $sample ? $pagination->items() : pagination($pagination);
    }

    /**
     * 通过角色ID列表获取菜单ID.
     */
    public function getMenuIdsByRoleIds(array $ids): array
    {
        if (empty($ids)) {
            return [];
        }
        return SystemRole::whereIn('id', $ids)
            ->with(['menus' => function (Query $query) {
                $query->field('id')->order('sort', 'desc');
            }])->select()->toArray();
    }

    public function updateRoleMenu($id, array $data): bool
    {
        $menuIds = $data['menu_ids'] ?? [];
        SystemRole::where('id', $id)->update([
            'updated_by' => $this->getUid(),
            'updated_at' => date('Y-m-d H:i:s')
        ]);
        if ($id != $this->isAdminRoleId()) {
            $role = SystemRole::query()->find($id);
            if ($role) {
                !empty($menuIds) && $role->menus()->sync(array_unique($menuIds));
                return true;
            }
        }
        return false;
    }

    public function update($id, array $data)
    {
        $data = array_merge($data, [
            'updated_by' => $this->getUid(),
            'updated_at' => date('Y-m-d H:i:s')
        ]);
        return SystemRole::where('id', $id)->update($data);
    }


    public function updateSort($data): array
    {
        return [true, SystemRole::update([
            'sort' => $data['numberValue']
        ], ['id' => Arr::get($data, 'id')])];
    }

    public function changeStatus($data): array
    {
        return [true, SystemRole::update([
            'status' => $data['status']
        ], ['id' => Arr::get($data, 'id')])];
    }

    /**
     * 删除
     * @param $id
     * @param $adminId
     * @return array
     */
    public function del($id, $adminId = 0)
    {
        $model = SystemRole::update([
            'deleted_at' => date('Y-m-d H:i:s'),
            'updated_at' => date('Y-m-d H:i:s'),
            'updated_by' => $this->getUid($adminId),
        ], ['id' => $id]);
        return [true, $model];
    }

    protected function isAdminRoleId()
    {
        return 1;
    }
}